package com.dream.inspect.modules.business.controller;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.dream.inspect.common.exception.RRException;
import com.dream.inspect.common.utils.DateUtils;
import com.dream.inspect.common.utils.DatetimeUtil;
import com.dream.inspect.modules.app.constants.AttrConstants;
import com.dream.inspect.modules.app.controller.common.CommonMethod;
import com.dream.inspect.modules.business.dao.SuperviseProjectRecordDao;
import com.dream.inspect.modules.business.dao.SuperviseRecordDao;
import com.dream.inspect.modules.business.dao.SuperviseTargetDao;
import com.dream.inspect.modules.business.entity.SuperviseProjectRecordEntity;
import com.dream.inspect.modules.business.entity.SuperviseTargetEntity;
import com.dream.inspect.modules.business.entity.SuperviseTempletEntity;
import com.dream.inspect.modules.business.service.*;
import com.dream.inspect.modules.dream.pojo.SuperviseRecordFormMap;
import com.dream.inspect.modules.dream.pojo.SysUserFormMap;
import com.dream.inspect.modules.job.common.ScheduleCommonMethod;
import com.dream.inspect.modules.sys.controller.AbstractController;
import com.dream.inspect.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.R;
import com.dream.inspect.common.validator.ValidatorUtils;
import com.dream.inspect.modules.business.entity.SuperviseProjectEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;


/**
 * 督察立项表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-06-16 17:04:53
 */
@RestController
@RequestMapping("business/superviseproject")
public class SuperviseProjectController extends AbstractController{

    @Autowired
    private SuperviseProjectService superviseProjectService;
    @Autowired
    private SuperviseRecordDao superviseRecordDao;
    @Autowired
    SuperviseTempletService superviseTempletService;
    @Autowired
    SuperviseProjectRecordService superviseProjectRecordService;

    @Autowired
    SuperviseTargetService superviseTargetService;
    @Autowired
    ScheduleCommonMethod scheduleCommonMethod;
    @Autowired
    SuperviseTargetDao superviseTargetDao;
    @Autowired
    SuperviseProjectRecordDao superviseProjectRecordDao;

    @Autowired
    SysMessageService sysMessageService;
    @Autowired
    CommonMethod commonMethod;
    @Value("${config.winReporterDocPath}")
    private String winPath;
    @Value("${config.linuxReporterDocPath}")
    private String linuxPath;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:superviseproject:list")
    public R list(@RequestParam Map<String, Object> params){
            SysUserEntity user = getUser();
            /*if(!params.containsKey("flag")){
                params.put("flag","");
            }*/
            params.put("deptId", user.getDeptId());
            params.put("userId", user.getUserId());
        PageUtils page = superviseProjectService.findProjectList(params);
        return R.ok().put("page", page).put("sessionUser", getSessionUser());
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    /*@RequiresPermissions("business:superviseproject:info")*/
    public R info(@RequestParam Map<String, String> params){
        SuperviseProjectEntity spEntity = new SuperviseProjectEntity();
        spEntity = superviseProjectService.findSuperviseProjectById(params);

        return R.ok().put(AttrConstants.DATA, spEntity);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("business:superviseproject:save")
    public R save(@RequestBody SuperviseProjectEntity superviseProject){
        superviseProjectService.insert(superviseProject);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("business:superviseproject:update")
    public R update(@RequestBody SuperviseProjectEntity superviseProject){
        ValidatorUtils.validateEntity(superviseProject);
        superviseProjectService.updateAllColumnById(superviseProject);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("business:superviseproject:delete")
    public R delete(@RequestBody Long[] ids){
        superviseProjectService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 督察记录
     * @param params
     * @return
     */
    @RequestMapping("/getSuperviseRecord")
    public R getSuperviseRecord(@RequestParam Map<String, Object> params){
        List<SuperviseRecordFormMap> list = superviseRecordDao.findSuperviseRecordByProjectId(params);
        return R.ok().put(AttrConstants.DATA, list);
    }
    /**
     * 项目进程
     * @param params
     * @return
     */
    @RequestMapping("/getProjectProcess")
    public R getProjectProcess(@RequestParam Map<String, Object> params){
        List<SuperviseProjectRecordEntity> list = superviseProjectRecordDao.findProjectProcess(params);
        return R.ok().put(AttrConstants.DATA, list);
    }
    /**
     * 执行单位
     * @param params
     * @return
     */
    @RequestMapping("/getExecuteDept")
    public R getExecuteDept(@RequestParam Map<String, Object> params){
        List<SuperviseTargetEntity> list = superviseTargetDao.getExecuteProjectListById(params);
        return R.ok().put(AttrConstants.DATA, list);
    }

    /**
     * 查询所有模板根据用户
     */
    @ResponseBody
    @RequestMapping("/findAllModel")
    public R findAllModel() {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("flag","3");
        params.put("deptId",getDeptId());
        List<SuperviseTempletEntity> list = superviseTempletService.findAllModelToUserIdList(params);
        return R.ok().put("data", list);
    }

    /**
     * 督察立项insert
     *
     * @param params (督察立项相关信息)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertSuperviseProject",method={RequestMethod.GET,RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public R insertSuperviseProject(@RequestParam Map<String, String> params, @RequestParam(value = "file", required = false) MultipartFile file , HttpServletRequest request){

        try {
//            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//            MultipartFile file = multipartRequest.getFile("file");
            if(file != null){
                String origName = file.getOriginalFilename();
                int index = origName.lastIndexOf("\\");
                String fileName = origName.substring(index + 1);
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                if ( !"DOC".equals(suffix) && !"DOCX".equals(suffix)) {
                    return R.error("2","专项文档只能上传word格式文件");
                }
                /*String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                if (fileName.indexOf(File.separator) != -1) {
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                }*/
                String url=uploadOneFileList(file,  request);
                params.put("filePath",url);
                params.put("fileName",fileName);
            }
            // 督察立项表
            params.put("userId",String.valueOf(getUserId()));
            params.put("lxrq",DateUtils.format(new Date()));
            params.put("projectJsonInfo",(params.get("ids") + ""));
            String id = params.get("id");
            if (StringUtils.isEmpty(id)) {
            	Long spId = superviseProjectService.insertSuperviseProject(params);
                if (spId == 0L) {
                    return R.error("申请立项失败！");
                } else {
                    //督察专项进程记录表
                    params.put("czzt","1");
                    params.put("userName",getUser().getName());
                    params.put("userDeptId",params.get("zbdwId"));
                    superviseProjectRecordService.insertSuperviseProjectRecordService(params, spId);
                    //督察对象表
                    insertSuperviseTarget(params, spId);
                    scheduleCommonMethod.addTimeMessage(DateUtils.stringToDate(params.get("jzrq"), DateUtils.DATE_TIME_PATTERN),"2",spId+"");

                }
            } else {
        		 // 督察立项表
                params.put("lxspzt","0");
                boolean blnFlag = superviseProjectService.updateSuperviseProject(params);
                
                if (!blnFlag) {
                	return R.error("处理失败！");
                }
                //督察专项进程记录表
                params.put("czzt","1");
                params.put("userName",getUser().getName());
                params.put("userDeptId",params.get("zbdwId"));
                //督察专项进程记录表
            	superviseProjectRecordService.insertSuperviseProjectRecordService(params, Long.valueOf(id));
                //删除督察对象的数据
                superviseTargetService.deleteSuperviseTargetByCondition(params);
                //督察对象表
            	insertSuperviseTarget(params, Long.valueOf(id));
                scheduleCommonMethod.addTimeMessage(DateUtils.stringToDate(params.get("jzrq"), DateUtils.DATE_TIME_PATTERN),"2",id);
            }
            //insert sys_message
            String noticeTitle = "您有新的立项待审批";
            params.put("noticeTitle", noticeTitle);
            String contentText = "您有新的立项" + params.get("titleName") + "待审批";
            params.put("noticeContent", contentText);
            String deptId = params.get("deptId");
            String roles = "";
            if (StringUtils.isNotEmpty(deptId)) {
                roles = commonMethod.getRolesAByDeptId(deptId); //接收角色
            }
            if (StringUtils.isNotEmpty(roles)) {
                params.put("roles", roles);
            }
            sysMessageService.insertMessage(params);
        } catch (RRException rre) {
            System.out.println(rre.getMessage());
            return R.error(rre.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("申请立项失败！");
        }

        return R.ok();
    }

    /**
     * 文件上传
     * @param multipartFile
     * @param request
     * @return
     * @throws Exception
     */
    public String uploadOneFileList(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
        List<String> newFileNames = new ArrayList<>();
        String os = System.getProperty("os.name");
        String newPath = null;
        String today = DatetimeUtil.getDateyyyyMMddhhmmss();
        //String newFileName = null;
        //newFileName = UUID.randomUUID() + originalFilename;
        if (os.toLowerCase().startsWith("win")) {
//            newPath = winPath + UUID.randomUUID() + "/";
            newPath = winPath + "doc/" + today + "/";
        } else {
            newPath = linuxPath + "doc/" + today + "/";
        }
        try {
            //文件的原始名称
            String originalFilename = multipartFile.getOriginalFilename();
            //
            if (multipartFile != null && originalFilename != null && originalFilename.length() > 0) {

                //存储图片的物理路径
                //String pic_path = request.getSession().getServletContext().getRealPath("/upload");
                //如果文件夹不存在则创建
                File file = new File(newPath);
                if (!file.exists()) {
                    System.out.println("file not exists");
                    file.mkdirs();
                }
                /**
                 * 获取新文件的File实例,通过spring的org.springframework.web.multipartInterface MultipartFile
                 * 下的transferTo方法,这个可以移动文件的文件系统,复制文件系统中的文件或内存内容保存到目标文件.
                 * 如果目标文件已经存在,它将被删除。
                 */
                //新文件路径实例
                File targetFile = new File(newPath, originalFilename);
                //内存数据读入磁盘
                multipartFile.transferTo(targetFile);
                newFileNames.add(originalFilename);
            }
            return newPath+originalFilename;
        } catch (IOException e) {
            throw new Exception();
        }
    }
    private void insertSuperviseTarget(Map<String, String> params, Long spId) {

        String dcssfwList = params.get("ids") + "";
        if(StringUtils.isNotEmpty(dcssfwList)) {
            dcssfwList = dcssfwList.replaceAll("\\\\","");
            List<SuperviseTargetEntity> stList = JSON.parseArray(dcssfwList, SuperviseTargetEntity.class);
            String userId = params.get("userId");
            if (stList != null && stList.size() > 0) {
                for (SuperviseTargetEntity temp : stList) {
                    temp.setProjectId(spId);
                    temp.setCreateUser(Long.valueOf(userId));           //创建人id
                    temp.setUpdateUser(Long.valueOf(userId));           //更新人id
                    temp.setSsStatus("0");
                    //督察对象表
                    superviseTargetService.insertSuperviseTarget(temp);
                }
            }
        }

    }
}
